package com.tanhua.server.interceptor;

import com.tanhua.server.pojo.User;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.NoAuthorization;
import com.tanhua.server.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    //注入UserService对象
    @Autowired
    private UserService userService;




    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //判断,请求的方法是否包含了NoAuthorization注解,包含则直接放行,不包含则执行下面的操作
        if (handler instanceof HandlerMethod){
           HandlerMethod handlerMethod= (HandlerMethod) handler;
           NoAuthorization annotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
           if (annotation!=null){
               return true;
           }
       }


        String token = request.getHeader("Authorization");
        User user = this.userService.queryUserByToken(token);
        if (null==user){
            response.setStatus(401);//无权限访问
            return false;
        }

        UserThreadLocal.set(user);
        return true;
    }
}
